package pl.edu.agh.pros.internal.proxy.service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.ros.exception.ServiceException;

import pl.edu.agh.pros.util.ServiceObjectLatch;

//TODO what if Service fails and no response comes for specific time - agent that will set null future objects
public final class ServiceResponseManager<A> {

	private Map<UUID, ServiceObjectLatch<A>> futureObjectsMap = new HashMap<UUID, ServiceObjectLatch<A>>();

	public synchronized ServiceObjectLatch<A> createFutureObject(UUID objectId) {
		ServiceObjectLatch<A> futureObject = new ServiceObjectLatch<A>();
		futureObjectsMap.put(objectId, futureObject);
		return futureObject;
	}

	// TODO what on exception ? how to pass proper Exception to client
	public synchronized void onResponseArrived(UUID objectId, A response) {
		ServiceObjectLatch<A> futureObject = futureObjectsMap.remove(objectId);
		if (futureObject != null) {
			futureObject.set(response);
		}
	}

	public synchronized void onExceptionArrived(UUID uuid, ServiceException e) {
		ServiceObjectLatch<A> futureObject = futureObjectsMap.remove(uuid);
		if (futureObject != null) {
			futureObject.onException(e);
		}
	}

	public UUID generateObjectId() {
		return UUID.randomUUID();
	}

}
